package com.leyou.user.service;


import com.leyou.common.utils.CodecUtils;
import com.leyou.common.utils.NumberUtils;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.pojo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String KEY_PREFIX = "user:code:phone:";

    private static final Logger logger = LoggerFactory.getLogger(UserService.class);


    public Boolean checkUserData(String data, Integer type) {

        User record = new User();

        switch (type) {
            case 1:
                record.setUsername(data);
                break;
            case 2:
                record.setPhone(data);
                break;
            default:
                return null;
        }
        return this.userMapper.selectCount(record) == 0;

    }

    /**
     * 生成短信验证码
     *
     * @param phone
     * @return
     */
    public Boolean sendVerifyCode(String phone) {
        //生成验证码
        String code = NumberUtils.generateCode(6);

        try {
            //发送短信
            Map<String, String> msg = new HashMap<>();
            msg.put("phone", phone);
            msg.put("code", code);
            //第一个参数交换机名称，第二个参数是队列名称。第三个参数是队列需要的数据类型封装的类型
            this.amqpTemplate.convertAndSend("ly.sms.exchange", "sms.verify.code", msg);
            //将code存入Redis 存入的第一个参数为key，第二个参数是验证码，第三个是时间一到自动消亡，第四个是时间单位。
            this.redisTemplate.opsForValue().set(KEY_PREFIX + phone, code, 5, TimeUnit.MINUTES);
            return true;
        } catch (Exception e) {
            logger.error("发送短信失败。phone：{}， code：{}", phone, code);
            return false;
        }
    }


    /**
     * 用户注册
     *
     * @param code
     * @return
     */
    public Boolean register(User user, String code) {

        String key = KEY_PREFIX + user.getPhone();
        // 从redis取出验证码
        String codeCache = this.redisTemplate.opsForValue().get(key);

        if (!code.equals(codeCache)) {

            return false;
        }
        user.setId(null);
        user.setCreated(new Date());

        // 生成盐
        String salt = CodecUtils.generateSalt();
        user.setSalt(salt);

        try {
            //盐值加密密码
            user.setPassword(CodecUtils.md5Hex(user.getPassword(),salt));
        } catch (Exception e) {
            logger.error("MD5密码加密失败手机号为：{}", user.getPhone(), e);
        }

      Boolean boo =  this.userMapper.insertSelective(user) == 1;

        if(boo){
            try {
                this.redisTemplate.delete(key);
            } catch (Exception e) {
                logger.error("删除缓存验证码失败，code：{}", code, e);
            }
        }

        return boo;
    }

    public User queryUser(String username, String password) {

        // 查询
        User record = new User();
        record.setUsername(username);
        User user = this.userMapper.selectOne(record);
        // 校验用户名
        if (user == null) {
            return null;
        }
        // 校验密码
        if (!user.getPassword().equals(CodecUtils.md5Hex(password, user.getSalt()))) {
            return null;
        }
        // 用户名密码都正确
        return user;

    }
}
